"""
推荐系统命令行接口
"""

import argparse
import sys
import os
import json
from datetime import datetime

# 添加src目录到路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from recommendation.hybrid_recommender import HybridRecommender
from recommendation.cold_start import ColdStartRecommender

def setup_argparse():
    """设置命令行参数"""
    parser = argparse.ArgumentParser(description='电影推荐系统')
    
    parser.add_argument('--user-id', type=int, required=True, 
                       help='要推荐的目标用户ID')
    parser.add_argument('--top-k', type=int, default=10,
                       help='推荐数量 (默认: 10)')
    parser.add_argument('--model-path', type=str, 
                       default='models/best_hybrid_model',
                       help='模型路径 (默认: models/best_hybrid_model)')
    parser.add_argument('--data-path', type=str, default='data/processed/',
                       help='数据路径 (默认: data/processed/)')
    parser.add_argument('--output-format', choices=['table', 'json', 'simple'], 
                       default='table', help='输出格式')
    parser.add_argument('--diversity', action='store_true',
                       help='启用多样性推荐')
    parser.add_argument('--batch-users', type=str,
                       help='批量用户推荐文件路径（每行一个用户ID）')
    
    return parser

def print_recommendations_table(recommendations, user_id):
    """以表格形式打印推荐结果"""
    print(f"\n🎬 为用户 {user_id} 的个性化推荐")
    print("=" * 80)
    print(f"{'排名':<4} {'电影ID':<8} {'评分':<6} {'年份':<6} {'电影标题':<40} {'类型':<20}")
    print("-" * 80)
    
    for i, rec in enumerate(recommendations, 1):
        title = rec['title'][:38] + '..' if len(rec['title']) > 40 else rec['title']
        genres = rec['genres'][:18] + '..' if len(rec['genres']) > 20 else rec['genres']
        
        print(f"{i:<4} {rec['movieId']:<8} {rec['predicted_rating']:<6} "
              f"{rec.get('year', '未知'):<6} {title:<40} {genres:<20}")
    
    print("=" * 80)

def print_simple_recommendations(recommendations, user_id):
    """简化格式打印推荐结果"""
    print(f"\n为用户 {user_id} 的推荐结果:")
    for i, rec in enumerate(recommendations, 1):
        print(f"{i}. {rec['title']} (评分: {rec['predicted_rating']})")

def main():
    """主函数"""
    parser = setup_argparse()
    args = parser.parse_args()
    
    print("🚀 电影推荐系统启动...")
    print(f"📁 模型路径: {args.model_path}")
    print(f"📁 数据路径: {args.data_path}")
    
    try:
        # 检查模型文件是否存在
        if not os.path.exists(args.model_path):
            print(f"⚠️  模型文件不存在: {args.model_path}")
            print("🔄 使用冷启动推荐器...")
            recommender = ColdStartRecommender(args.data_path)
            
            if args.batch_users:
                print("❌ 冷启动模式不支持批量用户推荐")
                return
            
            recommendations = recommender.recommend_popular(args.top_k)
            
            # 输出结果
            if args.output_format == 'json':
                print(json.dumps(recommendations, ensure_ascii=False, indent=2))
            else:
                print_simple_recommendations(recommendations, args.user_id)
                
            return
        
        # 使用混合推荐器
        recommender = HybridRecommender(args.model_path, args.data_path)
        
        # 批量用户推荐
        if args.batch_users:
            print(f"📊 批量用户推荐模式: {args.batch_users}")
            with open(args.batch_users, 'r') as f:
                user_ids = [int(line.strip()) for line in f if line.strip()]
            
            results = recommender.batch_recommend(user_ids, args.top_k)
            
            # 保存结果到文件
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_file = f"recommendations_batch_{timestamp}.json"
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(results, f, ensure_ascii=False, indent=2)
            
            print(f"✅ 批量推荐结果已保存到: {output_file}")
            
        else:
            # 单个用户推荐
            print(f"👤 目标用户: {args.user_id}")
            print(f"📊 推荐数量: {args.top_k}")
            print(f"🎯 多样性模式: {'开启' if args.diversity else '关闭'}")
            
            recommendations = recommender.recommend(
                args.user_id, 
                top_k=args.top_k, 
                diversity=args.diversity
            )
            
            # 输出结果
            if args.output_format == 'json':
                print(json.dumps(recommendations, ensure_ascii=False, indent=2))
            elif args.output_format == 'simple':
                print_simple_recommendations(recommendations, args.user_id)
            else:
                print_recommendations_table(recommendations, args.user_id)
        
        print("✅ 推荐完成！")
        
    except Exception as e:
        print(f"❌ 推荐过程出错: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()